/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.emergency.bean.MaterialHiddenDanger;
import com.koron.emergency.domain.EmergencyMaterial;
import com.koron.emergency.domain.MaterialCheckRecord;
import com.koron.emergency.domain.MaterialCheckRelation;
import com.koron.emergency.service.api.MaterialCheckRecordService;
import com.koron.emergency.util.BusinessCode;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(tags = "materialCheckRecord",description = "应急物资-检查记录接口")
@RestController
@RequestMapping("/materialCheckRecord")
public class MaterialCheckRecordController {
    private final static Logger logger = LoggerFactory.getLogger(MaterialCheckRecordController.class);
    @Autowired
    private MaterialCheckRecordService service;

    @Autowired
    private Util util;
    @ApiOperation("保存检查记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id，新增不传，修改必传",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkEmployeeCode", value = "检查负责人code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkEmployeeName", value = "检查负责人姓名", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "executerCode", value = "检查执行人code，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "executerName", value = "检查执行人姓名，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkDeptCode", value = "被检查的单位code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkDeptName", value = "被检查的单位名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkTime", value = "检查日期时间", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "description", value = "描述",  dataType = "String",paramType = "query")
    })
    @RequestMapping(value = "/save.htm",method = RequestMethod.POST)
    @Log(title = "保存检查记录", businessModule = "应急物资-检查记录", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<String> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore MaterialCheckRecord checkRecord){
        if (null==user){
            MessageBean<String> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        if (StringUtils.isNotEmpty(checkRecord.getExecuterCode())){
            String []codes=checkRecord.getExecuterCode().split("[,，]");
            checkRecord.setExecuterCode(new Gson().toJson(Arrays.asList(codes)));
        }

        if (StringUtils.isNotEmpty(checkRecord.getExecuterName())){
            String []names=checkRecord.getExecuterName().split("[,，]");
            checkRecord.setExecuterName(new Gson().toJson(Arrays.asList(names)));
        }
        checkRecord.setUpdateTime(new Date());
        checkRecord.setUpdateUserName(user.getName());
        checkRecord.setUpdateUser(user.getCode());
        return service.save(checkRecord);
    }

    @ApiOperation("提交检查记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "jobsTasksId",value = "任务id",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/commit.htm",method = RequestMethod.POST)
    @Log(title = "提交检查记录", businessModule = "应急物资-检查记录", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> commit(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,@RequestParam final String id,@RequestParam(required = false) final String jobsTasksId){
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return service.commit(user,id,jobsTasksId);
    }

    @ApiOperation("删除应急物资检查记录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/delete.htm",method = RequestMethod.POST)
    @Log(title = "删除应急物资检查记录", businessModule = "应急物资-检查记录", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> delete(@RequestParam final String id){

        return service.delete(id);
    }

    @ApiOperation("查询单个检查记录详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/details.htm",method = RequestMethod.POST)
    public MessageBean<MaterialCheckRecord> details(@RequestParam final String id){

        return service.queryOne(id);
    }

    @ApiOperation("应急物资-检查记录列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "title",value = "检查记录标题",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkEmployeeName",value = "检查负责人名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "executerName",value = "检查执行人名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "status",value = "状态，1草稿2提交",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/list.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<MaterialCheckRecord>> list(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String title, @RequestParam(required = false) final String checkEmployeeName,
                                                           @RequestParam(required = false) final String executerName,@RequestParam(required = false) final Integer status,
                                                       @RequestParam(required = false) String keyword,@RequestParam Integer page, @RequestParam Integer pageSize){
        Integer start=null;
        if (page==null||page<=0){
            page=1;
            if (pageSize==null||pageSize<=0){
                pageSize=15;
            }
        }
        start=(page<=1)?0:(page-1)*pageSize;
        MessageBean<DataBean<MaterialCheckRecord>>msg= service.queryByCondition(corpCode, title,checkEmployeeName, executerName, status, start, pageSize,keyword);
        if (null!=msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("应急物资-检查记录-上传附件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "keepFiles",value = "要保存的附件地址，多个之间用，分开",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "delFiles",value = "要删除的附件地址，多个之间用，分开",required = true,dataType = "String",paramType = "query"),
    })
    @Log(title = "应急物资-检查记录-上传附件接口", businessModule = "应急物资-检查记录", businessManipulation = BusinessManipulation.UPDATE)
    @RequestMapping(value = "/saveCheckAttachment.htm",method = RequestMethod.POST)
    public MessageBean<Integer> saveCheckAttachment(@RequestParam final String id, @RequestParam final MultipartFile[] files,String keepFiles,String delFiles){
        return  service.saveCheckAttachment(id,files,keepFiles,delFiles);
    }

//    @ApiOperation("应急物资-检查记录-删除附件")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
//            @ApiImplicitParam(name = "delFiles",value = "要删除的文件地址",required = true,dataType = "String",paramType = "query")
//    })
//    @Log(title = "应急物资-检查记录-删除附件", businessManipulation = BusinessManipulation.UPDATE)
//    @RequestMapping(value = "/deleteAttachment.htm",method = RequestMethod.POST)
//    public MessageBean<Integer> deleteAttachment(@RequestParam final String id, @RequestParam final String delFiles){
//        return  service.deleteAttachment(id,delFiles);
//    }
    @ApiOperation("应急物资-检查记录-附件列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/fileList.htm",method = RequestMethod.POST)
    public MessageBean<?> fileList(@RequestParam final String id){
        return service.fileList(id);
    }

    @ApiOperation("应急物资-检查记录明细列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkRecordId",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkEmployeeCode",value = "检查负责人code",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/queryCheckDeatilsList.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<EmergencyMaterial>> queryCheckDeatilsList(@RequestParam(required = false) final String corpCode,@RequestParam(required = false) final String checkRecordId,
                                                                          @RequestParam(required = false) final   String checkEmployeeCode,  @RequestParam Integer page,  @RequestParam Integer pageSize){
        Integer start=null;
        if (page==null||page<=0){
            page=1;
            if (pageSize==null||pageSize<=0){
                pageSize=15;
            }
        }
        start=(page<=1)?0:(page-1)*pageSize;
        return service.queryCheckDeatils(corpCode,checkRecordId,  checkEmployeeCode.split("_")[0], start, pageSize);
    }

    @ApiOperation("应急物资-检查记录单条明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkRecordId",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkEmployeeCode",value = "检查负责人code",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "emergencyMaterialId",value = "应急物资id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/queryOneCheckDeatils.htm",method = RequestMethod.POST)
    public MessageBean<EmergencyMaterial> queryOneCheckDeatils(@RequestParam(required = false) final String corpCode,@RequestParam(required = false) final String checkRecordId,
                                                                          @RequestParam(required = false) final   String checkEmployeeCode,  @RequestParam String emergencyMaterialId){
        return service.queryOneCheckDeatils(corpCode,checkRecordId,  checkEmployeeCode.split("_")[0], emergencyMaterialId);
    }

    @ApiOperation("应急物资-检查记录单条检查隐患记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "materialCheckRecordId",value = "检查记录id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "materialId",value = "应急物资id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/queryOneDeviceOfDanger.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<HiddenDangerDiscovery>> queryOneDeviceOfDanger(@RequestParam(required = false) final String corpCode,@RequestParam(required = false) final String materialCheckRecordId,
                                                                         @RequestParam String materialId,@RequestParam(required = false) Integer page,@RequestParam(required = false) Integer pageSize){
        return service.queryOneDeviceOfDanger(corpCode, materialId, materialCheckRecordId,page,pageSize);
    }

    @ApiOperation("存储应急物资检查结果明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app必传",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceId", value = "设备Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "normal", value = "是否正常,0异常，1正常",  dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "hiddenDangers", value = "隐患列表json格式",  dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/saveRealtion.htm",method = RequestMethod.POST)
    @Log(title = "新增、修改设备检查结果明细", businessModule = "应急物资-检查记录", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> saveRealtion(HttpServletRequest request, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String userCode,
                                             @RequestParam String materialCheckRecordId, @RequestParam String materialId, @RequestParam(required = false) Boolean normal,
                                             @RequestParam(required = false) String hiddenDangers){
        MessageBean<Integer> msg=new MessageBean<>();
        if (null == user) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        MaterialCheckRelation relation=new MaterialCheckRelation();
        relation.setMaterialCheckRecordId(materialCheckRecordId);
        relation.setMaterialId(materialId);
        relation.setNormal(normal);

        List<MaterialHiddenDanger> materialHiddenDangers = JSONObject.parseArray(hiddenDangers, MaterialHiddenDanger.class);
        relation.setMaterialHiddenDangerList(materialHiddenDangers);
        //get multipartfiles
        if (materialHiddenDangers != null && !materialHiddenDangers.isEmpty()) {
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                    StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                    for (int i = 0; i < materialHiddenDangers.size(); i++) {
                        MaterialHiddenDanger materialHiddenDanger = materialHiddenDangers.get(i);
                        materialHiddenDanger.setFiles(standardMultipartHttpServletRequest.getFiles("files" + i));
                    }
                }
            }
        }
        return service.saveRealtion(user,relation);
    }

    @ApiOperation("保存应急物资检查隐患")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app必传",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "materialCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "materialId", value = "设备Id", required = true, dataType = "String", paramType = "query"),
     })
    @RequestMapping(value = "/saveCheckDanger.htm",method = RequestMethod.POST)
    @Log(title = "新增、修改设备检查结果明细", businessModule = "应急物资-检查记录", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> saveCheckDanger(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String userCode,
                                             @RequestParam String materialCheckRecordId, @RequestParam String materialId, HiddenDangerDiscovery discovery,
                                                String delFileAddress, String keepFileAddress, MultipartFile[] files) {
        MessageBean<?> msg=new MessageBean<>();
        if (null == user) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }

        return service.saveCheckDanger(user, materialCheckRecordId, materialId, discovery, delFileAddress, keepFileAddress, files);
    }
    @ApiOperation("应急物资-检查记录-删除附件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "检查记录id",required = true,dataType = "String",paramType = "query")
    })
    @RequestMapping(value = "/viewReport.htm",method = RequestMethod.POST)
    public MessageBean<?> viewReport(String checkRecordId){
        return service.viewReport(checkRecordId);
    }

    @ApiOperation("应急物资-检查明细-详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "materialId",value = "物资id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "materialCheckId",value = "检查记录id",required = true,dataType = "String",paramType = "query")
    })
    @RequestMapping(value = "/queryRelationDeatils.htm",method = RequestMethod.POST)
    public MessageBean<MaterialCheckRelation> queryRelationDeatils(@RequestParam final String materialId,@RequestParam final String materialCheckId){
        return service.queryRelationDeatils(materialId,materialCheckId);
    }


    @ApiOperation("应急物资-检查记录列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "title",value = "检查记录标题",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkEmployeeName",value = "检查负责人名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "executerName",value = "检查执行人名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "status",value = "状态，1草稿2提交",dataType = "int",paramType = "query"),
    })
    @RequestMapping(value = "/exportList.htm", method = RequestMethod.GET)
    public HttpEntity<?> exportList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String corpCode,
                                    String title, String checkEmployeeName,String executerName,Integer status) {
        if (null == user) {
            return null;
        }
        List<MaterialCheckRecord> list = service.exportList(user, corpCode,title,checkEmployeeName,executerName,status);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/materialCheckRecordList.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/materialCheckRecordList.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("应急物资-检查记录列表", targetFile, "materialCheckRecordList.btl", map);
    }
}
